class UsersController < ApplicationController
  before_action :logged_in_user, only: [:edit, :update]

  def show
    @user = User.find(params[:id])
    @products = Product.all
  end

  def new
    @user = User.new
  end

  def create
    @user = User.new(user_params)
    if @user.save
      log_in(@user)
      # 处理注册成功的情况
      flash[:success] = "Welcome to the SHOP!"
      redirect_to @user
    else
      render 'new'
    end
  end

  def edit
    @user = User.find(params[:id])
  end

  def update
    @user = User.find(params[:id])
    if @user.update_attributes(user_params)
      # 处理更新成功的情况 else
    else
      render 'edit' 
    end
  end

  private

  def user_params
    params.require(:user).permit(:username, :password, :nickname, :password_confirmation)
  end

  # 确保用户已登录
  def logged_in_user
    unless logged_in?
      flash.now[:danger] = "请登录"
      redirect_to login_url
    end
  end
end
